import { Injectable, UseFilters } from '@nestjs/common';
import { LoginDto, RegisterUserDto } from './dto/user.dto';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { equals, isNil, isEmpty } from 'ramda';
import { LoginDoType } from 'src/common/auth/constants';
import { HttpExceptionFilter } from 'src/common/http-exception.filter';
import { UserEntity } from 'src/modules/admin/user/entities/user.entity';
import { errorState, getPagination, getStatus, successState, throwHttp } from 'src/utlis';
import { Between, Connection, Raw, Repository } from 'typeorm';
import { compareSync, hashSync } from 'bcryptjs';
import { UpdateUserInfoDto } from 'src/modules/admin/user/dto/user.dto';
import { Status } from 'src/dictionaries/index.enum';
import { PageDto } from 'src/common/dto/dto';
import { isTrue } from 'src/utlis/tools';
const dayjs = require('dayjs')
import { v4 as uuidv4 } from 'uuid';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(UserEntity)
    private readonly userRepository: Repository<UserEntity>,
    private readonly jwtService: JwtService,
    private readonly connection: Connection,

  ) { }
  /** 登录 */
  @UseFilters(new HttpExceptionFilter())
  async login(params: LoginDto) {
    const { mobile, password } = params;
    const user = await this.userRepository
      .createQueryBuilder("user").where('user.mobile = :mobile ', { mobile })
      .select(['user.email', 'user.password', 'user.id', 'user.status', 'user.mobile']).getOne();
    if (!user) {
      throwHttp('用户不存在');
    }
    if (!compareSync(password, user.password)) {
      throwHttp('用户名或密码不正确');
    }
    if (equals(Number(user.status), 20)) {
      throwHttp('该账号已被禁用，请联系管理员处理');
    }
    /** 更新登录时间 */
    await this.userRepository
      .createQueryBuilder()
      .update(UserEntity)
      .set({
        accessDate: new Date(),
      })
      .where('id = :id', { id: user.id })
      .execute();
    const payload = {
      username: user.username,
      userId: user.id,
      mobile: user.mobile,
      type: LoginDoType.User
    };
    // 把信息存在token
    return {
      token: this.jwtService.sign(payload),
      ...user
    };
  }

  // 注册
  @UseFilters(new HttpExceptionFilter())
  async registerUser(params: RegisterUserDto): Promise<string> {
    try {
      const { mobile, password } = params;
      const userInfo = await this.userRepository
        .createQueryBuilder("user").where('user.mobile = :mobile', { mobile }).getOne();
      if (!isNil(userInfo)) {
        throwHttp('手机号已注册');
        return;
      }
      const user = new UserEntity();
      user.username = '新用户';
      user.mobile = mobile;
      user.password = password;
      const result = await this.userRepository.manager.save(user);
      if (!isEmpty(result)) {
        return `注册成功`;
      }
      throwHttp('注册失败');
    } catch (error) {
      throwHttp(error.message);
    }
  }
  /** 修改用户信息 */
  @UseFilters(new HttpExceptionFilter())
  async updateUserInfo(body: UpdateUserInfoDto, userId: number) {
    try {
      const { username, QQ, mobile, avatar, description, gender, birthdayDate } = body
      const userInfo = await this.userRepository.findOne({
        where: { id: userId, status: Status.ENABLED },
        select: ['id'],
      });
      if (isNil(userInfo)) {
        throwHttp('用户不存在');
        return;
      }
      const { affected } = await this.userRepository
        .createQueryBuilder()
        .update(UserEntity)
        .set({
          username, QQ, mobile, avatar, description, gender, birthdayDate
        })
        .where('id = :id', { id: userId })
        .execute();
      if (affected) {
        return '用户信息修改成功';
      }
      throwHttp('用户信息修改失败');
    } catch (error) {
      throwHttp(error.message);
    }
  }
  /** 获取用户信息 */
  @UseFilters(new HttpExceptionFilter())
  async getUserInfo(id: number, relations = []): Promise<UserEntity> {
    try {
      if (!id) {
        throwHttp('参数为空');
      }
      const data = await this.userRepository.findOne({
        where: { id, status: Status.ENABLED },
        relations
      });
      if (isNil(data)) {
        throwHttp('用户不存在');
        return;
      }
      return data;
    } catch (error) {
      throwHttp(error.message);
    }
  }
  /**
  * 更新用户信息
  * @param queryRunner 查询运行器
  * @param userId 用户ID
  * @param data 更新用户数据
  * @returns 是否成功
  */
  async updateUser(queryRunner, userId, data) {
    const user = await this.getUserInfo(userId, []);
    if (!isTrue(user)) errorState('用户不存在');
    const { affected } = await queryRunner.manager
      .createQueryBuilder()
      .update(UserEntity)
      .set(data)
      .where('id = :id', { id: userId })
      .execute();

    return affected > 0;
  }

}
